<?php

declare(strict_types = 1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Model;

use App\Traits\Instance;
use App\Traits\ModelFunctions;
use App\Traits\MysqlTable;
use Hyperf\Database\Model\Builder;
use Hyperf\DbConnection\Model\Model as BaseModel;

abstract class Model extends BaseModel
{
    use Instance;
    use MysqlTable;
    use ModelFunctions;

    /**
     * Indicates if the model should be timestamped.
     *
     * @var bool
     */
    public $timestamps = true;
    // 时间字段的类型：时间戳
    protected $dateFormat = 'U';
    /**
     * The name of the "created at" column.
     *
     * @var string
     */
    const CREATED_AT = 'created_time';
    /**
     * The name of the "updated at" column.
     *
     * @var string
     */
    const UPDATED_AT = 'updated_time';
    /**
     * The connection name for the model.
     *
     * @var string
     */
    protected $connection = 'default';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [];
    // 黑名单
    protected $guarded = [];
    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends      = [];
    protected    $is_delete    = 1;// 是否删除：0.假删除；1.真删除【默认全部假删除】
    public    $delete_field = 'is_delete';//删除字段
    // 开启月分表
    const MONTH_SUB_TABLE = false;

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        //var_dump($this->getTable());
    }

    protected function boot() : void
    {
        parent::boot(); // TODO: Change the autogenerated stub

        // 软删除，自动追加where条件
        if ($this->is_delete == 0){
            static::addGlobalScope($this->delete_field, function(Builder $builder){
                return $builder->where($this->delete_field, $this->is_delete);
            });
        }
    }

    /**
     * 分页列表
     *
     * @param         $model
     * @param  array  $with_model
     * @param  int    $limit
     *
     * @return array
     */
    public function getPaginate($model, array $with_model = [], int $limit = 10) : array
    {
        $where = [];
        if ( $this->is_delete == 0 ) $where = ['is_delete' => '0'];
        $list = $model->where($where)->with($with_model)->paginate($limit);
        return ['data' => $list->items(), 'current_page' => $list->currentPage(), 'current_total' => $list->count(), 'per_page' => $list->perPage(), 'limit' => $list->perPage(), 'total' => $list->total(), 'last_page' => $list->lastPage(),];
    }

    public function setPaginate($list) : array
    {
        return ['data' => $list->items(), 'current_page' => $list->currentPage(), 'current_total' => $list->count(), 'per_page' => $list->perPage(), 'limit' => $list->perPage(), 'total' => $list->total(), 'last_page' => $list->lastPage(),];
    }

    /**
     * 下拉列表
     *
     * @return \Hyperf\Database\Model\Builder[]|\Hyperf\Database\Model\Collection
     */
    public function getSelectLists($sort = 'DESC')
    {
        $model = $this->query();
        // 是否开启了假删除
        if ( $this->is_delete == 0 ) $model = $model->where(['is_delete' => '0']);
        return $model->orderBy($this->primaryKey, $sort)->get();
    }

    /**
     * 新增数据
     *
     * @param  array  $params
     * @param  int    $start_filter：是否开启自动过滤字段（只会录入当前表的字段）
     *
     * @return \Hyperf\Database\Model\Builder|\Hyperf\Database\Model\Model
     */
    public function add(array $params, int $start_filter = 1)
    {
        return $this->query()->create($start_filter === 1 ? $this->setFilterFields($params) : $params);
    }

    /**
     * 更新数据
     *
     * @param $params
     *
     * @return int
     */
    public function edit($params)
    {
        $primaryKey = $this->getKeyName();
        $id = $params[$primaryKey];
        return $this->whereUpdate([$primaryKey => $id], $this->setFilterFields($params));
    }

    /**
     * 删除/批量批量
     *
     * @param $ids
     *
     * @return int
     */
    public function batch_delete($ids) : int
    {
        $primary = $this->getKeyName();
        $operating_state = 0;
        $ids = is_string($ids) ? explode(',', $ids) : [$ids];
        switch (intval($this->is_delete)) {
            case 0:
                $operating_state = $this->cnpscyWhereIn($primary, $ids)->update([$this->delete_field => 1]);
                break;
            case 1:
                $operating_state = $this->cnpscyWhereIn($primary, $ids)->delete();
                break;
        }
        return $operating_state;
    }

    /**
     * [changeFiledStatus 指定字段变更]
     *
     * @param  array  $request_data  [description]
     *
     * @return [type]               [description]
     */
    public function changeFiledStatus($request_data = []) : bool
    {
        $primary = $this->getKeyName();
        if ( empty($request_data[$primary]) ) {
            $this->setError('主键为必填项');
            return false;
        }
        $alert_prefix = '{ ' . $primary . ' => ' . $request_data[$primary] . ' }';
        if ( empty($this_model = $this->find($request_data[$primary])) ) {
            $this->setError($alert_prefix . '不存在！');
            return false;
        }

        if ( $this->whereUpdate([$primary => $request_data[$primary]], [$request_data['change_field'] => $request_data['change_value']]) ) {
            $this->setError($alert_prefix . '设置成功！');
            return true;
        } else {
            $this->setError($alert_prefix . '设置失败！');
            return false;
        }
    }
}